package com.rc.saas.tenant.controller.printer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.StdRequest;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.elec.ElecStationExample;
import com.rc.saas.tenant.model.hlhtsk.HlhtskTenant;
import com.rc.saas.tenant.model.printer.ElecPrinter;
import com.rc.saas.tenant.model.printer.ElecPrinterExample;
import com.rc.saas.tenant.model.printer.ElecPrinterRecord;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.hlhtsk.HlhtskTenantService;
import com.rc.saas.tenant.service.printer.ElecPrinterRecordService;
import com.rc.saas.tenant.service.printer.ElecPrinterService;
import com.rc.saas.tenant.util.PubFetchTool;
import com.rc.saas.tenant.vo.printer.BaselessStartPrintReq;
import com.rc.saas.tenant.vo.printer.NothingPrintReq;
import com.rc.saas.tenant.vo.printer.PrinterRecordSearch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Create by Yang on 2021/7/27
 */

@Controller
@RequestMapping("/printerRecord")
public class PrinterRecordController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String prefix = "/templates/printer";

    @Autowired
    private ElecStationService elecStationService;


    @Autowired
    private ElecPrinterService elecPrinterService;

    @Autowired
    private HlhtskTenantService hlhtskTenantService;

    @Autowired
    private ElecPrinterRecordService elecPrinterRecordService;


    protected final String TENANT_CODE = "914401153";



    /**
     * 跳转首页列表
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        List <ElecStation> elecStations = elecStationService.selectByExample(new ElecStationExample());
        model.addAttribute("pileGroups", elecStations);
        return prefix + "/printerRecord";
    }


    /**
     * 返回列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPagePrinterRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPagePrinterRecord(PrinterRecordSearch search) {

        //int offset;
        //int limit;
        PageInfo<ElecPrinterRecord> page = elecPrinterRecordService.selectPageBySearch(search, search.getOffset(), search.getLimit());
        WebPageInfo webPageInfo = new WebPageInfo(page.getList(), Long.valueOf(page.getTotal()).intValue());
        return webPageInfo;
    }

    /*
     * 重置
     * */
    @RequestMapping("/reSet")
    @ResponseBody
    public TResponse updatePrintCount(Long id) {
        try {
            elecPrinterRecordService.updatePrintCountById(id);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("重置失败");
        }
    }

    /*
     * 保存凭空打印订单
     * 打印
     * */
    @RequestMapping("/savePrintOrder")
    @ResponseBody
    public Object savePrintOrder(BaselessStartPrintReq baselessStartPrintReq) {
        //String url = printerServer + "/cservice/baselessPrint";
        //String body = "";
        //CloseableHttpClient httpClient = HttpClients.createDefault();
        //HttpPost httpPost = new HttpPost(url);
        //List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        //nvps.add(new BasicNameValuePair("carNum", baselessStartPrintReq.getCarNum()));
        //nvps.add(new BasicNameValuePair("chargeAmount", baselessStartPrintReq.getChargeAmount()));
        //nvps.add(new BasicNameValuePair("endTime", baselessStartPrintReq.getEndTime()));
        //nvps.add(new BasicNameValuePair("epgName", baselessStartPrintReq.getEpgName()));
        //nvps.add(new BasicNameValuePair("epNo", baselessStartPrintReq.getEpNo()));
        //nvps.add(new BasicNameValuePair("orderNum", baselessStartPrintReq.getOrderNum()));
        //nvps.add(new BasicNameValuePair("power", baselessStartPrintReq.getPower()));
        //nvps.add(new BasicNameValuePair("priRtua", baselessStartPrintReq.getPriRtua()));
        //nvps.add(new BasicNameValuePair("soc", baselessStartPrintReq.getSoc()));
        //nvps.add(new BasicNameValuePair("startTime", baselessStartPrintReq.getStartTime()));
        //try {
        //    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        //    CloseableHttpResponse response1 = httpClient.execute(httpPost);
        //    HttpEntity entity = response1.getEntity();
        //    if (entity != null) {
        //        body = EntityUtils.toString(entity, "utf-8");
        //    }
        //    response1.close();
        //
        //} catch (Exception e) {
        //    e.printStackTrace();
        //
        //return JSONObject.parseObject(body);
        //}
        try {
            NothingPrintReq nothingPrintReq = new NothingPrintReq();
            nothingPrintReq.setCarNum(baselessStartPrintReq.getCarNum());
            nothingPrintReq.setChargeAmount(baselessStartPrintReq.getChargeAmount());
            nothingPrintReq.setStartTime(baselessStartPrintReq.getStartTime());
            nothingPrintReq.setEndTime(baselessStartPrintReq.getEndTime());
            nothingPrintReq.setEpgName(baselessStartPrintReq.getStationName());
            nothingPrintReq.setEpNo(baselessStartPrintReq.getEpNo());
            nothingPrintReq.setOrderNum(baselessStartPrintReq.getOrderNum());
            nothingPrintReq.setPower(baselessStartPrintReq.getPower());
            nothingPrintReq.setPriRtua(baselessStartPrintReq.getPriRtua());
            nothingPrintReq.setSoc(baselessStartPrintReq.getSoc());

            //加密
            ObjectMapper objectMapper = new ObjectMapper();
            String enData = objectMapper.writeValueAsString(nothingPrintReq);
            HlhtskTenant hlhtskTenant = hlhtskTenantService.selectByTenantCode(TENANT_CODE);
            String data = PubFetchTool.genDDEncodeData(hlhtskTenant, enData);

            StdRequest resp = new StdRequest();
            resp.setData(data);
            resp.setSeq(TENANT_CODE);

            TResponse tResponse = TResponse.SUCCESS();
            logger.info("凭空打印返回状态码及数据:{},{}", tResponse.getStatus(), tResponse.getMessage(), tResponse.getData());

            return tResponse;
        } catch (Exception e) {
            logger.error("凭空打印失败报错:", e);
            return TResponse.FAIL("服务器错误，请查看日志");
        }

    }

    /*
     * 凭空打印订单页面
     * */
    @RequestMapping("/printOrder")
    public String printOrder(Model model) {

        ElecStationExample elecStationExample = new ElecStationExample();
        elecStationExample.createCriteria().andTenantCodeEqualTo(TENANT_CODE);

        List<ElecStation> elecStations = elecStationService.selectByExample(elecStationExample);
        model.addAttribute("elecStations", elecStations);
        String orderNum = "s" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                + UUID.randomUUID().toString().substring(24);//订单号:时间戳到毫秒+uuid后12位
        model.addAttribute("orderNum", orderNum);
        List<ElecPrinter> printerList = elecPrinterService.selectByExample(new ElecPrinterExample());
        model.addAttribute("printerList", printerList);
        return prefix + "/printOrder";
    }


    /*
     * 根据id获取桩群名称 打印机逻辑地址
     * */
    @RequestMapping("/selectStationNamePrirtuaById")
    @ResponseBody
    public TResponse selectStationNamePrirtuaById(Long id) {
        ElecStation elecStation = elecStationService.selectByPrimaryKey(id);

        //获取打印机
        ElecPrinter elecPrinter = elecPrinterService.selectByPrimaryKey(elecStation.getPrinterId());
        if (elecPrinter == null) {
            ElecPrinterExample elecPrinterExample = new ElecPrinterExample();
            elecPrinterExample.createCriteria().andElecStationIdEqualTo(elecStation.getElecStationId())
                    .andOperateStatusEqualTo("1");
            List<ElecPrinter> elecPrinters = elecPrinterService.selectByExample(elecPrinterExample);
            if (!CollectionUtils.isEmpty(elecPrinters)) {
                elecPrinter = elecPrinters.get(0);
            }

        }
        if (elecPrinter == null) {
            return TResponse.FAIL("当前桩群没有打印机");
        }
        Map map = new HashMap();
        map.put("stationName", elecStation.getStationName());
        map.put("priRtua", elecPrinter.getPrinterRtua());
        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put(map);
        return tResponse;
    }


    /*
     * 凭空打印查询桩群
     * */
    /*
     * 根据id获取桩群名称 打印机逻辑地址
     * */
    @RequestMapping("/selectStationNamePrirtuaByName")
    @ResponseBody
    public TResponse selectStationNamePrirtuaByName(String stationName) {
        ElecStationExample example = new ElecStationExample();
        example.createCriteria().andStationNameLike("%" + stationName + "%")
                .andTenantCodeEqualTo(TENANT_CODE);
        List<ElecStation> pileGroups = elecStationService.selectByExample(example);
        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put(pileGroups);
        return tResponse;
    }
}
